package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.LongYanUtil;
import com.block.datapush.service.apipush.utils.QuJiHuaUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 龙焱 半流程
 */
@Service
public class LongYanApiBService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;
    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone_md5", memberSourceInfo.getMobileMd5());
        bizMap.put("working_city", memberSourceInfo.getCity());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("name_md5", SecureUtil.md5(memberSourceInfo.getRealname()));
        bizMap.put("idno_md5", SecureUtil.md5(memberSourceInfo.getIdcard()));
        bizMap.put("sex", memberSourceInfo.getSex()==1?1:2);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("gjj", LongYanUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("shebao", LongYanUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("loan_amount", LongYanUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("house", LongYanUtil.getHouse(memberSourceInfo.getHouse()));
        Integer car = LongYanUtil.getCar(memberSourceInfo.getCar());
        bizMap.put("car", car);
        if(StrUtil.equals(String.valueOf(car),"1")){
            bizMap.put("car_status", 1);
            bizMap.put("car_price", 99);
        }

        bizMap.put("overdue", LongYanUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("zhima", LongYanUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("occupation", LongYanUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("insurance", LongYanUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("data", encrypt);

        log.info("【龙焱半流程】撞库开始【queryUrl】{}【bizMap】{}【headerMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(headerMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(headerMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【龙焱半流程】撞库结束【result】{}", resultObject);

        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        JSONObject data = resultObject.getJSONObject("data");
        pushApiResult.setCode(code+"");
        pushApiResult.setMessage(message);
        pushApiResult.setResultInfo(result);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));

        if(StrUtil.equals(String.valueOf(code),"0")){
            String url = data.getString("agreement_url");
            String orderId = data.getString("order_id");
            pushApiResult.setApproveUrl(url);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            pushApiResult.setOutOrderNo(orderId);
            extJson.put("orderId", orderId);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String price = data.getString("price");//下游返回分润前价格
                BigDecimal piceNew = new BigDecimal(price);
                if (piceNew == null || piceNew.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceRight = piceNew.divide(typeRate);//分润后价格
                pushApiResult.setPrice(priceRight);
                pushApiResult.setPriceRight(piceNew);
            }
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getRegisterUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String orderId = extJson.getString("orderId");

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("order_id", orderId);

        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("data", encrypt);

        log.info("【龙焱半流程】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(headerMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(headerMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【龙焱半流程】导单结束【result】{}", resultObject);
        String code = resultObject.getString("code");
        String url = resultObject.getString("data");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code +"|");
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if(StrUtil.equals(String.valueOf(code),"0")){
            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);
        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String orderId = jsonObject.getString("order_id");

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(orderId));
        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("message","success");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


}
